#import "TimeTools.h"
#import "TimerOper.h"

void* TimeTools_New()
{
	TimerOper *pTimerOper = [[TimerOper alloc] init];
	return pTimerOper;
}

void TimeTools_Start(void *p, void (*pCallBack)(void *pCBObj), void *pCBObj, int aTime, TBOOL aIsLoop)
{
	TimerOper *pTimerOper = (TimerOper *)p;
	pTimerOper.pCall->pCBObj = pCBObj;
	pTimerOper.pCall->pCallBack = pCallBack;
  pTimerOper.bLoop = (aIsLoop==TRUE);
	pTimerOper.pTimer = [NSTimer scheduledTimerWithTimeInterval:aTime/1000.0 target:pTimerOper selector:@selector(CallBack:) userInfo:nil repeats:aIsLoop];
}

void TimeTools_Stop(void* aTimer)
{
	TimerOper *pTimerOper = (TimerOper *)aTimer;
	
	if (pTimerOper.pTimer) {
		if ([pTimerOper.pTimer isValid]) {
			[pTimerOper.pTimer invalidate];
		}
    pTimerOper.pTimer = NULL;
	}
}

void TimeTools_Free(void* aTimer)
{
	TimerOper *pTimerOper = (TimerOper *)aTimer;
	
	if (pTimerOper.pTimer) {
		if ([pTimerOper.pTimer isValid]) {
			[pTimerOper.pTimer invalidate];
		}
    pTimerOper.pTimer = NULL;
	}
	
	[pTimerOper release];
}

void TimeTools_GetNowDate(char *pText)
{
	NSDate *date = [NSDate date];
	NSCalendar *calendar = [NSCalendar currentCalendar];
	NSDateComponents *comps;
	
	// 年月日获得
	comps = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) 
						fromDate:date];
	NSInteger year = [comps year];
	NSInteger month = [comps month];
	NSInteger day = [comps day];
	
//	//当前的时分秒获得
//	comps = [calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit)
//						fromDate:date];
//	NSInteger hour = [comps hour];
//	NSInteger minute = [comps minute];
//	NSInteger second = [comps second];
//	NSLog(@"hour: %d minute: %d second: %d", hour, minute, second);
	
	// 周几和星期几获得
	comps = [calendar components:(NSWeekCalendarUnit | NSWeekdayCalendarUnit | NSWeekdayOrdinalCalendarUnit)
						fromDate:date];
//	NSInteger week = [comps week]; // 今年的第几周
	NSInteger weekday = [comps weekday]; // 星期几（注意，周日是“1”，周一是“2”。。。。）
//	NSInteger weekdayOrdinal = [comps weekdayOrdinal]; // 这个月的第几周
	

	
	
	char sw[32];
	memset(sw, 0, sizeof(sw));
	switch (weekday) {
		case 1:
			strcpy(sw,"星期日");
			break;
		case 2:
			strcpy(sw,"星期一");
			break;
		case 3:
			strcpy(sw,"星期二");
			break;
		case 4:
			strcpy(sw,"星期三");
			break;
		case 5:
			strcpy(sw,"星期四");
			break;
		case 6:
			strcpy(sw,"星期五");
			break;
		case 7:
			strcpy(sw,"星期六");
			break;
	} 
	
	sprintf(pText, "%04d/%02d/%02d %s",year,month,day, sw);
}